<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="音频名称" prop="musicName">
            <el-input
              v-model="queryParams.musicName"
              placeholder="请输入音频名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="音频大小" prop="musicSize">
            <el-input
              v-model="queryParams.musicSize"
              placeholder="请输入音频大小"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              style="width: 340px"
              v-model="dateRange"
              type="datetimerange"
              align="right"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['12:00:00', '08:00:00']">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-tooltip class="item" effect="dark" content="提示:上传音频最好不能大于1mb(否则可能上传失败)" placement="top-start">
              <el-upload :data="{ username: this.userName }" :action="'http://127.0.0.1:7888/music/audioUpload'" :show-file-list="false"
                         :on-success="handleFileUploadSuccess" :before-upload="beforeFileUpload" style="display: inline-block">
                <el-button size="mini" type="primary" class="ml-5" plain><i class="el-icon-top"></i>上传音频文件</el-button>
              </el-upload>
            </el-tooltip>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="listMusic" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="musicList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="音频编号" align="center" key="musicId" prop="musicId" v-if="columns[0].visible" />
          <el-table-column label="音频名称" align="center" key="musicName" prop="musicName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="音频大小" align="center" key="musicSize" prop="musicSize" v-if="columns[2].visible" :show-overflow-tooltip="true" />kb
          <el-table-column label="上传作者" align="center" key="createBy" prop="createBy" v-if="columns[3].visible" width="120" />
          <el-table-column label="音频创建时间" align="center" prop="createTime" v-if="columns[4].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="修改用户" align="center" key="updateBy" prop="updateBy" v-if="columns[5].visible" width="120" />
          <el-table-column label="音频修改时间" align="center" prop="updateTime" v-if="columns[6].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="回显id" align="center" key="picId" prop="picId" v-if="columns[7].visible" width="120" />
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-play"
                @click="handlePlay(scope.row)"
              >播放</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="listMusic"
        />
      </el-col>
    </el-row>
    <!-- 音频播放弹窗 -->
    <el-dialog title="音频播放" :visible.sync="dialogVisible" width="30%" :before-close="stop">
      <template>
        <center>
          <audio
            :src="src"
            autoplay="autoplay"
            controls="controls"
            ref="audio"
          >Your browser does not support the audio element.</audio>
        </center>
      </template>
    </el-dialog>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :rules="rules"  :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="音频名称" prop="musicName">
              <el-input v-model="form.musicName" placeholder="请输入音频名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传作者" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入上传作者" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="音频大小" prop="musicSize">
              <el-input v-model="form.musicSize" placeholder="请输入音频大小" maxlength="11" readonly />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传时间" prop="createTime">
              <div class="block" style="width: 200px;" >
                  <el-date-picker
                    v-model="form.createTime"
                    type="datetime"
                    placeholder="选择日期时间">
                  </el-date-picker>
                </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMusic, delMusic, updateMusic, delMusics} from "@/api/music/music";
import { getToken } from "@/utils/auth";
import Cookies from "js-cookie";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 音频表格数据
      musicList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      src: "",
      dialogVisible: false,
      // 角色选项
      roleOptions: [],
      //获取当前登录用户名
      userName: '',
      user: JSON.parse(sessionStorage.getItem('sessionObj')),
      // 表单参数
      form: {
        musicName: undefined,
        musicSize: undefined,
        musicId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        remark: undefined
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        musicName: undefined,
        musicSize: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `音频编号`, visible: true },
        { key: 1, label: `音频名称`, visible: true },
        { key: 2, label: `音频大小`, visible: true },
        { key: 3, label: `上传作者`, visible: true },
        { key: 4, label: `音频创建时间`, visible: true },
        { key: 5, label: `修改用户`, visible: true },
        { key: 6, label: `修改时间`, visible: true },
        { key: 7, label: `回显id`, visible: true }
      ],
      // 表单校验
      rules: {
        musicName: [
          { required: true, message: "音频名称不能为空", trigger: "blur" },
        ],
        musicSize: [
          { required: true, message: "音频大小不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // 将输入的字符串转换成数字类型
              const numValue = parseFloat(value);
              if (isNaN(numValue)) {
                callback(new Error('请输入数字值'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
        }
        ],
        createTime: [
          { required: true, message: "上传时间不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "上传作者不能为空", trigger: "blur" },
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    // 将存储的数据解析为对象
    var data = JSON.parse(this.user.data);
    // 获取username
    this.userName = data.username;
    this.listMusic();
  },
  methods: {
    //播放组件
    handlePlay(row) {
      this.src = "http://101.43.223.224:8765/image/getVideoById?id="+row.picId;
      this.play();
    },
    //播放
    play() {
      this.dialogVisible = true;
      this.$refs.audio.play();
    },
    //音频暂停
    stop() {
      this.dialogVisible = false;
      this.$refs.audio.pause();
      this.$refs.audio.currentTime = 0;
    },
    //只能上传mp3格式
    beforeFileUpload(file) {
      const extension = file.name.split('.').pop().toLowerCase();
      const isMp3 = extension === 'mp3';
      const isSizeValid = file.size / 1024 / 1024 <= 1; // 文件大小限制为 1MB
      if (!isMp3 || !isSizeValid) {
        if (!isMp3) {
          this.$message.error('只能上传 mp3 格式的文件');
        }
        if (!isSizeValid) {
          this.$message.error('文件大小超过了限制');
        }
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
    //上传成功
    handleFileUploadSuccess(res) {
      console.log(res)
      this.$message.success("上传成功")
      this.listMusic()
    },
    /** 查询音频列表 */
    listMusic() {
      console.log()
      this.loading = true;
      listMusic(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
          this.musicList = res.data.data.content;
          this.total = res.data.data.totalSize;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.listMusic();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.musicName = ''
      this.queryParams.musicSize = ''
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.picId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row;
      this.open = true;
      this.title = "修改用户";
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.picId != undefined) {
            const date = new Date(this.form.createTime);
            const year = date.getFullYear();
            const month = ("0" + (date.getMonth() + 1)).slice(-2);
            const day = ("0" + date.getDate()).slice(-2);
            const hours = ("0" + date.getHours()).slice(-2);
            const minutes = ("0" + date.getMinutes()).slice(-2);
            const seconds = ("0" + date.getSeconds()).slice(-2);
            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            this.form.createTime = formattedDate;
            this.form.updateBy = this.userName;
            updateMusic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.listMusic();
            });
          } else {
            this.form.updateBy = this.userName;
            addMusic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.listMusic();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const picId = row.picId || this.ids;
      this.$modal.confirm('是否确认删除音频编号为"' + picId + '"的数据项？').then(function() {
        return delMusic(picId);
      }).then(() => {
        this.listMusic();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
<style>
  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 200px;
  }
</style>
